<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量执行脚本"
    width="60%"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="执行名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入批量执行名称"
        />
      </el-form-item>

      <el-form-item label="执行描述">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入批量执行描述（可选）"
        />
      </el-form-item>

      <el-form-item label="选中脚本" prop="scripts">
        <div class="scripts-container">
          <div class="scripts-header">
            <span>共选中 {{ scripts.length }} 个脚本</span>
          </div>
          
          <el-table :data="scripts" border size="small" max-height="300">
            <el-table-column prop="name" label="脚本名称" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>

      <el-form-item label="执行设置">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-checkbox v-model="formData.continue_on_error">
              执行失败时继续执行其他脚本
            </el-checkbox>
          </el-col>
          <el-col :span="12">
            <el-checkbox v-model="formData.parallel_execution">
              并行执行（实验性功能）
            </el-checkbox>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="预计耗时">
        <div class="time-estimate">
          <el-icon><Clock /></el-icon>
          <span>预计执行时间：{{ getEstimatedTime() }}</span>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleExecute" :loading="executing">
          <el-icon><VideoPlay /></el-icon>
          开始执行
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Clock, VideoPlay } from '@element-plus/icons-vue'
import { createUiAutomationBatchExecution } from '../../api/uiAutomation'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  scripts: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:visible', 'executed'])

// 响应式数据
const formRef = ref()
const executing = ref(false)

// 表单数据
const formData = reactive({
  name: '',
  description: '',
  continue_on_error: true,
  parallel_execution: false
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入执行名称', trigger: 'blur' },
    { min: 2, max: 200, message: '执行名称长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  scripts: [
    {
      validator: (rule, value, callback) => {
        if (props.scripts.length === 0) {
          callback(new Error('请选择要执行的脚本'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 方法
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    name: '',
    description: '',
    continue_on_error: true,
    parallel_execution: false
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const handleExecute = async () => {
  try {
    await formRef.value.validate()
    
    if (props.scripts.length === 0) {
      ElMessage.warning('请选择要执行的脚本')
      return
    }
    
    executing.value = true
    
    const requestData = {
      name: formData.name,
      description: formData.description,
      script_ids: props.scripts.map(script => script.id)
    }
    
    const response = await createUiAutomationBatchExecution(requestData)
    
    if (response.success) {
      ElMessage.success('批量执行任务已创建')
      emit('executed', response.data)
      handleClose()
    } else {
      ElMessage.error(response.message || '创建批量执行失败')
    }
  } catch (error) {
    console.error('创建批量执行失败:', error)
    ElMessage.error('创建批量执行失败')
  } finally {
    executing.value = false
  }
}

const getStatusType = (status) => {
  const statusMap = {
    'draft': '',
    'active': 'success',
    'inactive': 'info'
  }
  return statusMap[status] || ''
}

const getStatusText = (status) => {
  const statusMap = {
    'draft': '草稿',
    'active': '激活',
    'inactive': '停用'
  }
  return statusMap[status] || status
}

const getEstimatedTime = () => {
  const scriptCount = props.scripts.length
  if (scriptCount === 0) return '0分钟'
  
  // 假设每个脚本平均执行时间为2分钟
  const averageTime = 2
  const totalTime = formData.parallel_execution 
    ? Math.ceil(scriptCount / 3) * averageTime  // 假设最多3个并行
    : scriptCount * averageTime
  
  if (totalTime < 60) {
    return `${totalTime}分钟`
  } else {
    const hours = Math.floor(totalTime / 60)
    const minutes = totalTime % 60
    return `${hours}小时${minutes}分钟`
  }
}
</script>

<style lang="scss" scoped>
.scripts-container {
  .scripts-header {
    margin-bottom: 12px;
    font-weight: 600;
    color: #303133;
  }
}

.time-estimate {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-dialog) {
  .el-dialog__body {
    padding: 20px;
  }
}
</style>
